package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author 钟涛
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2021-12-21 09:49:21
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{
    @Autowired
    private UserInfoMapper userInfoMapper ;
    @Autowired
    private StringRedisTemplate redisTemplate ;
    @Override
    public UserInfo login(String loginName, String passwd) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper();
        wrapper.eq("login_name",loginName);
        wrapper.eq("passwd", MD5.encrypt(passwd));
        //1、去数据库对照
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        return userInfo;
    }

    /**
     * 处理登录成功的用户信息
     *
     * @param userInfo1
     * @param ip
     * @return
     * @throws JsonProcessingException
     */
    @Override
    public Map<String,String> handleLoginInfo(UserInfo userInfo1,String ip) throws JsonProcessingException {
        Map<String,String> resultMap = new HashMap<>();

        String token = UUID.randomUUID().toString().replace("-","");
        resultMap.put("token",token);
        resultMap.put("nickName",userInfo1.getNickName());
        //2、把token对应的当前用户信息放到redis中

        Map<String,Object> loginData = new HashMap<>();
        userInfo1.setPasswd(null);
        loginData.put("userId",userInfo1.getId());
        loginData.put("ip",ip);
        String key = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(loginData);
        redisTemplate.opsForValue().set(key,json,RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
        return resultMap;
    }

    @Override
    public void logout(String token) {
        String key = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(key);
    }
}




